package tx.bj12320.action;

import hirondelle.date4j.DateTime;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.struts2.ServletActionContext;
import org.josql.Query;
import org.josql.QueryExecutionException;
import org.josql.QueryParseException;

import cn.org.rapid_framework.beanutils.BeanUtils;
import cn.org.rapid_framework.web.scope.Flash;

import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javacommon.base.*;
import javacommon.util.*;

import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;

import tx.bj12320.model.*;
import tx.bj12320.model.enums.ActivityBPMNShapeEnum;
import tx.bj12320.model.enums.ActivityEnum;
import tx.bj12320.model.enums.ActivitySysUserTypeEnum;
import tx.bj12320.model.enums.BooleanEnum;
import tx.bj12320.model.enums.DdTypeEnum;
import tx.bj12320.model.enums.DelayStateEnum;
import tx.bj12320.model.enums.SysUserTypeEnum;
import tx.bj12320.model.enums.WorkOrderTypeEnum;
import tx.bj12320.dao.*;
import tx.bj12320.service.*;
import tx.bj12320.util.AppHelper;
import tx.bj12320.util.BPMNShape;
import tx.bj12320.util.WebUtils;
import tx.bj12320.vo.query.*;


public class TszbProcessInfoAction extends BaseStruts2Action implements Preparable,ModelDriven{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = "tszbProcessInfoId desc";

	//forward paths
	protected static final String QUERY_JSP = "/pages/TszbProcessInfo/query.jsp";
	protected static final String LIST_JSP= "/pages/TszbProcessInfo/list.jsp";
	protected static final String CREATE_JSP = "/pages/TszbProcessInfo/create.jsp";
	protected static final String EDIT_JSP = "/pages/TszbProcessInfo/edit.jsp";
	protected static final String SHOW_JSP = "/pages/TszbProcessInfo/show.jsp";
	//redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/pages/TszbProcessInfo/list.do";
	protected static final String userTasks_ACTION = "!/pages/TszbProcessInfo/userTasks.do";

	private TszbProcessInfoManager tszbProcessInfoManager;

	private TszbProcessInfo tszbProcessInfo;
	Long id = null;
	private String[] items;

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			tszbProcessInfo = new TszbProcessInfo();
		} else {
			tszbProcessInfo = (TszbProcessInfo)tszbProcessInfoManager.getById(id);
		}
	}

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setTszbProcessInfoManager(TszbProcessInfoManager manager) {
		this.tszbProcessInfoManager = manager;
	}

	public Object getModel() {
		return tszbProcessInfo;
	}

	public void setTszbProcessInfoId(Long val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/** 执行搜索 */
	public String list() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		Page page = tszbProcessInfoManager.findPage(query);
		savePage(page,query);
		return LIST_JSP;
	}

	/** 查看对象*/
	public String show() {
		return SHOW_JSP;
	}

	/** 进入新增页面*/
	public String create() {
		return CREATE_JSP;
	}

	private ProcessEngine processEngine;

	public void setProcessEngine(ProcessEngine processEngine) {
		this.processEngine = processEngine;
	}

	private RuntimeService runtimeService;
	private TaskService taskService;


	public void setRuntimeService(RuntimeService runtimeService) {
		this.runtimeService = runtimeService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public String deployProcess(){

		  // Get Activiti services
		  RepositoryService repositoryService = processEngine.getRepositoryService();
		  RuntimeService runtimeService = processEngine.getRuntimeService();
		  TaskService taskService = processEngine.getTaskService();
		  // Deploy the process definition
		  repositoryService.createDeployment()
		    .addClasspathResource("tx/bj12320/process/tousu_zhuanban.bpmn20.xml").addClasspathResource("tx/bj12320/process/tousu_zhuanban.png")
		    .deploy();
		return "";
	}

	private IdentityService identityService;

	public void setIdentityService(IdentityService identityService) {
		this.identityService = identityService;
	}

	private HistoryService historyService;

	public void setHistoryService(HistoryService historyService) {
		this.historyService = historyService;
	}

	public String initGroups(){
		LinkedHashMap<String, String> lm=ActivityEnum.toMap();
		Set<String> ls=lm.keySet();
		for (String l : ls) {
			identityService.saveGroup(identityService.newGroup(l+"_role"));
		}
		return "";
	}
	private OrgInfoManager orgInfoManager;
	public void setOrgInfoManager(OrgInfoManager manager) {
		this.orgInfoManager = manager;
	}


	/** 保存新增对象 */
	/**
	 * @deprecated
	 */
	public String save() {
		tszbProcessInfoManager.save(tszbProcessInfo);
		OrgInfo oi=orgInfoManager.getById(tszbProcessInfo.getOrgInfoId());
		Map<String, Object> vars = new HashMap<String, Object>();
		vars.put("tszbProcessInfoId", tszbProcessInfo.getTszbProcessInfoId());
		vars.put("orgInfoId", tszbProcessInfo.getOrgInfoId());
		vars.put("orgName", oi.getOrgName());
		vars.put("workOrderType", tszbProcessInfo.getWorkOrderType());

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("Tousu_zhuanban_process",tszbProcessInfo.getTszbProcessInfoId()+"",vars);

		Flash.current().success(CREATED_SUCCESS); //存放在Flash中的数据,在下一次http请求中仍然可以读取数据,error()用于显示错误消息
		return LIST_ACTION;
	}

	public String userTasks(){

		List<Task> tasks = taskService.createTaskQuery().taskCandidateUser(WebUtils.getUserInSession().getUserInfoId()+"").processDefinitionKey("Tousu_zhuanban_process").orderByTaskCreateTime().asc().list();

		List<TszbTask> ltts=new ArrayList<TszbTask>(tasks.size());
		for (Task task : tasks) {
			TszbTask tt=new TszbTask();
			tt.setTask(task);
//			log.info(task.getProcessInstanceId());
			TszbProcessInfo tpi=tszbProcessInfoManager.getByProcInstId(task.getProcessInstanceId());
			tt.setOrgInfoId(tpi.getOrgInfoId());
			tt.setOrgName(tpi.getOrgInfo().getOrgName());
			tt.setTszbProcessInfoId(tpi.getTszbProcessInfoId());
			tt.setWorkOrderType(tpi.getWorkOrderType());
			tt.setLastOperateIsPass(tpi.getLastOperateIsPass());
			UserInfo ui=tpi.getLastOperateUserInfo();
			if(ui!=null){
				tt.setLastOperateUserInfoRealName(ui.getRealName());
			}

			tt.setIsEmergency(tpi.getIsEmergency());

//			Map<String,Object> vars=taskService.getVariables(task.getId());
//			if(vars.size()>0){
//				tt.setOrgInfoId((Long)vars.get("orgInfoId"));
//				tt.setOrgName((String)vars.get("orgName"));
//				tt.setTszbProcessInfoId((Long)vars.get("tszbProcessInfoId"));
//				tt.setWorkOrderType((String)vars.get("workOrderType"));
//			}

			if(isNullOrEmptyString(tt.getIsEmergency())||tt.getIsEmergency()==0){
				ltts.add(tt);
			}else{
				ltts.add(0,tt);
			}
		}

		getRequest().setAttribute("tasks", ltts);
		return "/user-tasks.jsp";
	}

	/**
	 * @deprecated
	 * @return
	 */
	public String userTasksComplete(){

		List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery().finished().taskAssignee(WebUtils.getUserInSession().getUserInfoId()+"").orderByHistoricTaskInstanceEndTime().desc().list();

		List<TszbTaskComplete> ltts=new ArrayList<TszbTaskComplete>(tasks.size());
		for (HistoricTaskInstance task : tasks) {
			TszbTaskComplete tt=new TszbTaskComplete();
			tt.setTask(task);
			TszbProcessInfo tpi=tszbProcessInfoManager.getByProcInstId(task.getProcessInstanceId());
				tt.setOrgInfoId(tpi.getOrgInfoId());
				tt.setOrgName(tpi.getOrgInfo().getOrgName());
				tt.setTszbProcessInfoId(tpi.getTszbProcessInfoId());
				tt.setWorkOrderType(tpi.getWorkOrderType());

			ltts.add(tt);
		}

		getRequest().setAttribute("tasks", ltts);
		return "/user-tasks-complete.jsp";
	}


	public String tszbProcessInfoList() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);
		if(!WebUtils.getUserInSession().getSysUserType().equals(SysUserTypeEnum.BJ12320.getCode())){
			query.setOrgInfoId(orgInfoManager.getLevel1OrgInfo(WebUtils.getUserInSession().getOrgInfo()).getOrgInfoId());
		}
		Page page = tszbProcessInfoManager.findPage(query);
		savePage(page,query);
		return "/tszb/tszbProcessInfo-list.jsp";
	}
	/**
	 * 举报受理单明细统计报表-年报
	 * @return
	 */
	public String reportWorkOrderJbsldDetailYear() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime dt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=new DateTime(dt.getYear()+"-01-01").getStartOfMonth();
		DateTime end=new DateTime(dt.getYear()+"-12-31").getEndOfMonth();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderJbsldDetailResult(query,"procStartTimeMonth");

		return genReportExcel(tpirs,"report-work-order-jbsld-detail.xls");
	}
	/**
	 * 举报受理单明细统计报表-月报
	 * @return
	 */
	public String reportWorkOrderJbsldDetailMonth() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=sdt.getStartOfDay();
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateTime end=edt.getEndOfDay();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderJbsldDetailResult(query,"procStartTimeDate");

		return genReportExcel(tpirs,"report-work-order-jbsld-detail.xls");
	}
	/**
	 * 举报受理单明细统计报表-日报
	 * @return
	 */
	public String reportWorkOrderJbsldDetailDate() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(sdt.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(edt.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderJbsldDetailResult(query,"procStartTimeHour");

		return genReportExcel(tpirs,"report-work-order-jbsld-detail.xls");
	}
	private List<TszbProcessInfoReport> operateReportWorkOrderJbsldDetailResult(
			TszbProcessInfoQuery query,String procStartTime) {
		query.setPageSize(10000);
		Page page = tszbProcessInfoManager.findPage(query);

		List result=page.getResult();
		List<TszbProcessInfoReport> tpirs=new ArrayList<TszbProcessInfoReport>();

		for (Iterator iter = result.iterator(); iter.hasNext();) {
				TszbProcessInfo tpi=(TszbProcessInfo)iter.next();
				TszbProcessInfoReport tpir=new TszbProcessInfoReport();
				if(procStartTime.equals("procStartTimeMonth")){
					tpir.setReportDatetime(tpi.getProcStartTimeMonth());
				}else if(procStartTime.equals("procStartTimeDate")){
					tpir.setReportDatetime(tpi.getProcStartTimeDate());
				}else if(procStartTime.equals("procStartTimeHour")){
					tpir.setReportDatetime(tpi.getProcStartTimeHour());
				}

				tpir.setWorkOrderType(tpi.getWorkOrderType());
				tpir.setReportNum(1);

				tpir.setOrgInfoId(tpi.getOrgInfoId());
				tpir.setOrgName(tpi.getOrgInfo().getOrgName());
				tpir.setCallerNumber(tpi.getCallerNumber());
				tpir.setCallerName(tpi.getCallerName());
				tpir.setDealResult(tpi.getDealResult());
				tpir.setIncomingCallContent(tpi.getIncomingCallContent());
				tpir.setWorkOrderSort(tpi.getWorkOrderSort());

				tpirs.add(tpir);
			}
//		log.info(tpirs);
		return tpirs;
	}
	/**
	 * 表扬受理单明细统计报表-年报
	 * @return
	 */
	public String reportWorkOrderBysldDetailYear() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime dt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=new DateTime(dt.getYear()+"-01-01").getStartOfMonth();
		DateTime end=new DateTime(dt.getYear()+"-12-31").getEndOfMonth();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderBysldDetailResult(query,"procStartTimeMonth");

		return genReportExcel(tpirs,"report-work-order-bysld-detail.xls");
	}
	/**
	 * 表扬受理单明细统计报表-月报
	 * @return
	 */
	public String reportWorkOrderBysldDetailMonth() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=sdt.getStartOfDay();
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateTime end=edt.getEndOfDay();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderBysldDetailResult(query,"procStartTimeDate");

		return genReportExcel(tpirs,"report-work-order-bysld-detail.xls");
	}
	/**
	 * 表扬受理单明细统计报表-日报
	 * @return
	 */
	public String reportWorkOrderBysldDetailDate() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(sdt.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(edt.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderBysldDetailResult(query,"procStartTimeHour");

		return genReportExcel(tpirs,"report-work-order-bysld-detail.xls");
	}
	private List<TszbProcessInfoReport> operateReportWorkOrderBysldDetailResult(
			TszbProcessInfoQuery query,String procStartTime) {
		query.setPageSize(10000);
		Page page = tszbProcessInfoManager.findPage(query);

		List result=page.getResult();
		List<TszbProcessInfoReport> tpirs=new ArrayList<TszbProcessInfoReport>();

		for (Iterator iter = result.iterator(); iter.hasNext();) {
				TszbProcessInfo tpi=(TszbProcessInfo)iter.next();
				TszbProcessInfoReport tpir=new TszbProcessInfoReport();
				if(procStartTime.equals("procStartTimeMonth")){
					tpir.setReportDatetime(tpi.getProcStartTimeMonth());
				}else if(procStartTime.equals("procStartTimeDate")){
					tpir.setReportDatetime(tpi.getProcStartTimeDate());
				}else if(procStartTime.equals("procStartTimeHour")){
					tpir.setReportDatetime(tpi.getProcStartTimeHour());
				}

				tpir.setWorkOrderType(tpi.getWorkOrderType());
				tpir.setReportNum(1);

				tpir.setOrgInfoId(tpi.getOrgInfoId());
				tpir.setOrgName(tpi.getOrgInfo().getOrgName());
				tpir.setCallerNumber(tpi.getCallerNumber());
				tpir.setCallerName(tpi.getCallerName());
				tpir.setDealResult(tpi.getDealResult());
				tpir.setIncomingCallContent(tpi.getIncomingCallContent());
				tpir.setRelaPerson(tpi.getRelaPerson());

				tpirs.add(tpir);
			}
//		log.info(tpirs);
		return tpirs;
	}
/**
 * 工单明细统计报表-年报
 * @return
 */
public String reportWorkOrderDetailYear() {
	TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

	DateTime dt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
	DateTime start=new DateTime(dt.getYear()+"-01-01").getStartOfMonth();
	DateTime end=new DateTime(dt.getYear()+"-12-31").getEndOfMonth();
	DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	try {
		query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
		query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	List<TszbProcessInfoReport> tpirs = operateReportWorkOrderDetailResult(query,"procStartTimeMonth");

	return genReportExcel(tpirs,"report-work-order-detail.xls");
}
/**
 * 工单明细统计报表-月报
 * @return
 */
public String reportWorkOrderDetailMonth() {
	TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

	DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
	DateTime start=sdt.getStartOfDay();
	DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
	DateTime end=edt.getEndOfDay();
	DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	try {
		query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
		query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	List<TszbProcessInfoReport> tpirs = operateReportWorkOrderDetailResult(query,"procStartTimeDate");

	return genReportExcel(tpirs,"report-work-order-detail.xls");
}
/**
 * 工单明细统计报表-日报
 * @return
 */
public String reportWorkOrderDetailDate() {
	TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

	DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
	DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
	DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	try {
		query.setProcStartTimeBegin(df.parse(sdt.format("YYYY-MM-DD hh:mm:ss")));
		query.setProcStartTimeEnd(df.parse(edt.format("YYYY-MM-DD hh:mm:ss")));
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	List<TszbProcessInfoReport> tpirs = operateReportWorkOrderDetailResult(query,"procStartTimeHour");

	return genReportExcel(tpirs,"report-work-order-detail.xls");
}
private List<TszbProcessInfoReport> operateReportWorkOrderDetailResult(
		TszbProcessInfoQuery query,String procStartTime) {
	query.setPageSize(10000);
	Page page = tszbProcessInfoManager.findPage(query);

	List result=page.getResult();
	List<TszbProcessInfoReport> tpirs=new ArrayList<TszbProcessInfoReport>();

	for (Iterator iter = result.iterator(); iter.hasNext();) {
			TszbProcessInfo tpi=(TszbProcessInfo)iter.next();
			TszbProcessInfoReport tpir=new TszbProcessInfoReport();
			if(procStartTime.equals("procStartTimeMonth")){
				tpir.setReportDatetime(tpi.getProcStartTimeMonth());
			}else if(procStartTime.equals("procStartTimeDate")){
				tpir.setReportDatetime(tpi.getProcStartTimeDate());
			}else if(procStartTime.equals("procStartTimeHour")){
				tpir.setReportDatetime(tpi.getProcStartTimeHour());
			}

			tpir.setWorkOrderType(tpi.getWorkOrderType());
			tpir.setReportNum(1);

			tpir.setWorkOrderSort(tpi.getWorkOrderSort());
			tpir.setWorkOrderSortDdValue(tpi.getWorkOrderSortDdValue());
			DataDictQuery ddq =new DataDictQuery();
			ddq.setPageSize(10);
			if(tpi.getWorkOrderType().equals(WorkOrderTypeEnum.TSXTD.getCode())||tpi.getWorkOrderType().equals(WorkOrderTypeEnum.TSWXCGZD.getCode())){
				ddq.setDdType(DdTypeEnum.TSZB__WORK_ORDER_SORT_TSFL.getCode());
			}else if(tpi.getWorkOrderType().equals(WorkOrderTypeEnum.JYSLD.getCode())){
				ddq.setDdType(DdTypeEnum.TSZB__WORK_ORDER_SORT_JYFL.getCode());
			}

			ddq.setDdName(tpi.getWorkOrderSort());
			List ddql= dataDictManager.findPage(ddq).getResult();
			if(ddql.size()>0){
				log.info(ddql.size());
//				log.info(ddql);
				DataDict ddq3=(DataDict)ddql.get(0);
				if(ddq3.getDdLevel()==2){
					tpir.setWorkOrderSortLevel2(ddq3.getDdName());
				}else if(ddq3.getDdLevel()==1){
					tpir.setWorkOrderSortLevel2(ddq3.getDdName());
					tpir.setWorkOrderSortLevel1(ddq3.getDdName());
				}else if(ddq3.getDdLevel()==0){
					tpir.setWorkOrderSortLevel2(ddq3.getDdName());
					tpir.setWorkOrderSortLevel1(ddq3.getDdName());
				}else {
					DataDict ddq2=dataDictManager.getById(ddq3.getDdParentId());
					tpir.setWorkOrderSortLevel2(ddq2.getDdName());
					if(ddq2.getDdLevel()==2){
						tpir.setWorkOrderSortLevel2(ddq2.getDdName());
						DataDict ddq1=dataDictManager.getById(ddq2.getDdParentId());
						tpir.setWorkOrderSortLevel1(ddq1.getDdName());
					}else{
						tpir.setWorkOrderSortLevel1(ddq2.getDdName());
					}
				}
			}

			tpir.setOrgInfoId(tpi.getOrgInfoId());
			tpir.setOrgName(tpi.getOrgInfo().getOrgName());
			tpir.setOrgSysUserTypeName(SysUserTypeEnum.getByCode(tpi.getOrgInfo().getSysUserType()).getDesc());
//			log.info(SysUserTypeEnum.getByCode(tpi.getOrgInfo().getSysUserType()));
			OrgInfo oi=orgInfoManager.getByOrgCode(tpi.getOrgInfo().getParentOrgCode());
			if(oi!=null){
				tpir.setLevel1OrgInfoName(oi.getOrgName());
			}

			tpir.setCallerNumber(tpi.getCallerNumber());
			tpir.setCallerName(tpi.getCallerName());
			tpir.setZoneName(tpi.getZoneName());
			tpir.setShoulliPerson(tpi.getShoulliPerson());
			if(tpi.getWorkOrderDealTime()==null){//工单未办结
				tpir.setIsWorkOrderDealEnd(BooleanEnum.FALSE.getDesc());
			}else{
				tpir.setIsWorkOrderDealEnd(BooleanEnum.TRUE.getDesc());
				tpir.setWorkOrderDealTime(tpi.getWorkOrderDealTimeString());
				tpir.setWorkOrderDealDays(tpi.getWorkOrderDealDays());

			}
			tpir.setIsTrue(tpi.getIsTrue());
			tpir.setDealTime(tpi.getDealTimeString());
			tpir.setDealPerson(tpi.getDealPerson());
			tpir.setDealResult(tpi.getDealResult());
			tpir.setLeaderToshowSign(tpi.getLeaderToshowSign());
			tpir.setFeedbackRelaPersonTime(tpi.getFeedbackRelaPersonTimeString());
			tpir.setIncomingCallContent(tpi.getIncomingCallContent());
			tpir.setReceiveTime(tpi.getReceiveTimeString());

			tpirs.add(tpir);
		}
//	log.info(tpirs);
	return tpirs;
}
	/**
	 * 投诉工单分类统计报表-年报
	 * @return
	 */
	public String reportTsdWorkOrderSortYear() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime dt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=new DateTime(dt.getYear()+"-01-01").getStartOfMonth();
		DateTime end=new DateTime(dt.getYear()+"-12-31").getEndOfMonth();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportTsdWorkOrderSortResult(query,"procStartTimeMonth");

		return genReportExcel(tpirs,"report-tsd-work-order-sort.xls");
	}
	/**
	 * 投诉工单分类统计报表-月报
	 * @return
	 */
	public String reportTsdWorkOrderSortMonth() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=sdt.getStartOfDay();
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateTime end=edt.getEndOfDay();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportTsdWorkOrderSortResult(query,"procStartTimeDate");

		return genReportExcel(tpirs,"report-tsd-work-order-sort.xls");
	}
	/**
	 * 投诉工单分类统计报表-日报
	 * @return
	 */
	public String reportTsdWorkOrderSortDate() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(sdt.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(edt.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportTsdWorkOrderSortResult(query,"procStartTimeHour");

		return genReportExcel(tpirs,"report-tsd-work-order-sort.xls");
	}
	private List<TszbProcessInfoReport> operateReportTsdWorkOrderSortResult(
			TszbProcessInfoQuery query,String procStartTime) {
		query.setPageSize(10000);
		Page page = tszbProcessInfoManager.findPage(query);

		Collection result=page.getResult();
		List<TszbProcessInfoReport> tpirs=new ArrayList<TszbProcessInfoReport>();

		try {
			Query q = new Query ();
			q.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo GROUP BY workOrderSort, "+procStartTime);
			List res =q.execute (result).getResults();
			log.info(res);
		for (Iterator iter = res.iterator(); iter.hasNext();) {
			List ptd = (List) iter.next();
			if(ptd.get(0)==null||ptd.get(0).equals("null")) continue;
			Query q2 = new Query ();
				q2.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo Where workOrderSort='"+ptd.get(0)+"' and "+procStartTime+"='"+ptd.get(1)+"'");
				List r =q2.execute (result).getResults();
				TszbProcessInfo tpi=(TszbProcessInfo)r.get(0);
				TszbProcessInfoReport tpir=new TszbProcessInfoReport();
				tpir.setReportDatetime(ptd.get(1).toString());
				tpir.setWorkOrderType(ptd.get(0).toString());
				tpir.setReportNum(r.size());

				tpir.setWorkOrderSort(tpi.getWorkOrderSort());
				tpir.setWorkOrderSortDdValue(tpi.getWorkOrderSortDdValue());

				DataDictQuery ddq =new DataDictQuery();
				ddq.setPageSize(10);
				ddq.setDdType(DdTypeEnum.TSZB__WORK_ORDER_SORT_TSFL.getCode());
				ddq.setDdName(tpi.getWorkOrderSort());
				List ddql= dataDictManager.findPage(ddq).getResult();
				if(ddql.size()>0){
					log.info(ddql.size());
//					log.info(ddql);
					DataDict ddq3=(DataDict)ddql.get(0);
					if(ddq3.getDdLevel()==2){
						tpir.setWorkOrderSortLevel2(ddq3.getDdName());
					}else if(ddq3.getDdLevel()==1){
						tpir.setWorkOrderSortLevel2(ddq3.getDdName());
						tpir.setWorkOrderSortLevel1(ddq3.getDdName());
					}else {
						DataDict ddq2=dataDictManager.getById(ddq3.getDdParentId());
						tpir.setWorkOrderSortLevel2(ddq2.getDdName());
						if(ddq2.getDdLevel()==2){
							tpir.setWorkOrderSortLevel2(ddq2.getDdName());
							DataDict ddq1=dataDictManager.getById(ddq2.getDdParentId());
							tpir.setWorkOrderSortLevel1(ddq1.getDdName());
						}else{
							tpir.setWorkOrderSortLevel1(ddq2.getDdName());
						}
					}
				}


				Query q3 = new Query ();
				q3.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo Where isProcEnd=1");
				List r2 =q3.execute (r).getResults();
				tpir.setProcEndNum(r2.size());

				tpirs.add(tpir);
			}
		} catch (QueryParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (QueryExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		log.info(tpirs);
		return tpirs;
	}
	private DataDictManager dataDictManager;
	public void setDataDictManager(DataDictManager manager) {
		this.dataDictManager = manager;
	}
/**
 * 投诉未形成告知单统计报表-年报
 * @return
 */
public String reportTswxcgzdResolveWayYear() {
	TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

	DateTime dt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
	DateTime start=new DateTime(dt.getYear()+"-01-01").getStartOfMonth();
	DateTime end=new DateTime(dt.getYear()+"-12-31").getEndOfMonth();
	DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	try {
		query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
		query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	List<TszbProcessInfoReport> tpirs = operateReportTswxcgzdResolveWayResult(query,"procStartTimeMonth");

	return genReportExcel(tpirs,"report-tswxcgzd-resolve-way.xls");
}
/**
 * 投诉未形成告知单统计报表-月报
 * @return
 */
public String reportTswxcgzdResolveWayMonth() {
	TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

	DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
	DateTime start=sdt.getStartOfDay();
	DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
	DateTime end=edt.getEndOfDay();
	DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	try {
		query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
		query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	List<TszbProcessInfoReport> tpirs = operateReportTswxcgzdResolveWayResult(query,"procStartTimeDate");

	return genReportExcel(tpirs,"report-tswxcgzd-resolve-way.xls");
}
/**
 * 投诉未形成告知单统计报表-日报
 * @return
 */
public String reportTswxcgzdResolveWayDate() {
	TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

	DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
	DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
	DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	try {
		query.setProcStartTimeBegin(df.parse(sdt.format("YYYY-MM-DD hh:mm:ss")));
		query.setProcStartTimeEnd(df.parse(edt.format("YYYY-MM-DD hh:mm:ss")));
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	List<TszbProcessInfoReport> tpirs = operateReportTswxcgzdResolveWayResult(query,"procStartTimeHour");

	return genReportExcel(tpirs,"report-tswxcgzd-resolve-way.xls");
}
private List<TszbProcessInfoReport> operateReportTswxcgzdResolveWayResult(
		TszbProcessInfoQuery query,String procStartTime) {
	query.setPageSize(10000);
	Page page = tszbProcessInfoManager.findPage(query);

	Collection result=page.getResult();
	List<TszbProcessInfoReport> tpirs=new ArrayList<TszbProcessInfoReport>();

	try {
		Query q = new Query ();
		q.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo GROUP BY "+procStartTime);
		List res =q.execute (result).getResults();
		log.info(res);
		Query qg = new Query ();
		qg.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo GROUP BY resolveWay");
		List resg =qg.execute (result).getResults();
	for (Iterator iter = res.iterator(); iter.hasNext();) {
		List ptd = (List) iter.next();
		for (Iterator iterg = resg.iterator(); iterg.hasNext();) {
			List ptdg = (List) iterg.next();
			Query q2 = new Query ();
			q2.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo Where resolveWay='"+ptdg.get(0)+"' and "+procStartTime+"='"+ptd.get(0)+"'");
			List r =q2.execute (result).getResults();
			TszbProcessInfoReport tpir=new TszbProcessInfoReport();
			tpir.setReportDatetime(ptd.get(0).toString());
			tpir.setResolveWay(ptdg.get(0).toString());
			if(r.size()!=0){
				tpir.setReportNum(r.size());
			}
			tpirs.add(tpir);
		}

		}
	} catch (QueryParseException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	} catch (QueryExecutionException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
//	log.info(tpirs);
	return tpirs;
}
	/**
	 * 投诉工单网络单位统计报表-年报
	 * @return
	 */
	public String reportTsdOrgInfoYear() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime dt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=new DateTime(dt.getYear()+"-01-01").getStartOfMonth();
		DateTime end=new DateTime(dt.getYear()+"-12-31").getEndOfMonth();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportTsdOrgInfoResult(query,"procStartTimeMonth");

		return genReportExcel(tpirs,"report-tsd-org-info.xls");
	}
	/**
	 * 投诉工单网络单位统计报表-月报
	 * @return
	 */
	public String reportTsdOrgInfoMonth() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=sdt.getStartOfDay();
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateTime end=edt.getEndOfDay();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportTsdOrgInfoResult(query,"procStartTimeDate");

		return genReportExcel(tpirs,"report-tsd-org-info.xls");
	}
	/**
	 * 投诉工单网络单位统计报表-日报
	 * @return
	 */
	public String reportTsdOrgInfoDate() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(sdt.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(edt.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportTsdOrgInfoResult(query,"procStartTimeHour");

		return genReportExcel(tpirs,"report-tsd-org-info.xls");
	}
	private List<TszbProcessInfoReport> operateReportTsdOrgInfoResult(
			TszbProcessInfoQuery query,String procStartTime) {
		query.setPageSize(10000);
		Page page = tszbProcessInfoManager.findPage(query);

		Collection result=page.getResult();
		List<TszbProcessInfoReport> tpirs=new ArrayList<TszbProcessInfoReport>();

		try {
			Query q = new Query ();
			q.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo GROUP BY orgInfoId, "+procStartTime);
			List res =q.execute (result).getResults();
			log.info(res);
		for (Iterator iter = res.iterator(); iter.hasNext();) {
			List ptd = (List) iter.next();
			if(ptd.get(0)==null||ptd.get(0).equals("null")) continue;
			Query q2 = new Query ();
				q2.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo Where orgInfoId='"+ptd.get(0)+"' and "+procStartTime+"='"+ptd.get(1)+"'");
				List r =q2.execute (result).getResults();
				TszbProcessInfo tpi=(TszbProcessInfo)r.get(0);
				TszbProcessInfoReport tpir=new TszbProcessInfoReport();
				tpir.setReportDatetime(ptd.get(1).toString());
				tpir.setWorkOrderType(ptd.get(0).toString());
				tpir.setReportNum(r.size());
				tpir.setOrgInfoId(tpi.getOrgInfoId());
				tpir.setOrgName(tpi.getOrgInfo().getOrgName());
				tpir.setOrgSysUserTypeName(SysUserTypeEnum.getByCode(tpi.getOrgInfo().getSysUserType()).getDesc());
//				log.info(SysUserTypeEnum.getByCode(tpi.getOrgInfo().getSysUserType()));
				OrgInfo oi=orgInfoManager.getByOrgCode(tpi.getOrgInfo().getParentOrgCode());
				if(oi!=null){
					tpir.setLevel1OrgInfoName(oi.getOrgName());
				}

				tpirs.add(tpir);
			}
		} catch (QueryParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (QueryExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		log.info(tpirs);
		return tpirs;
	}
	/**
	 * 工单类型统计报表-年报
	 * @return
	 */
	public String reportWorkOrderTypeYear() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime dt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=new DateTime(dt.getYear()+"-01-01").getStartOfMonth();
		DateTime end=new DateTime(dt.getYear()+"-12-31").getEndOfMonth();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderTypeResult(query,"procStartTimeMonth");

		return genReportExcel(tpirs,"report-work-order-type.xls");
	}

	/**
	 * 工单类型统计报表-月报
	 * @return
	 */
	public String reportWorkOrderTypeMonth() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime start=sdt.getStartOfDay();
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateTime end=edt.getEndOfDay();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(start.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(end.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderTypeResult(query,"procStartTimeDate");

		return genReportExcel(tpirs,"report-work-order-type.xls");
	}

	/**
	 * 工单类型统计报表-日报
	 * @return
	 */
	public String reportWorkOrderTypeDate() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);

		DateTime sdt=new DateTime(getRequest().getParameter("procStartTimeBegin"));
		DateTime edt=new DateTime(getRequest().getParameter("procStartTimeEnd"));
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			query.setProcStartTimeBegin(df.parse(sdt.format("YYYY-MM-DD hh:mm:ss")));
			query.setProcStartTimeEnd(df.parse(edt.format("YYYY-MM-DD hh:mm:ss")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<TszbProcessInfoReport> tpirs = operateReportWorkOrderTypeResult(query,"procStartTimeHour");

		return genReportExcel(tpirs,"report-work-order-type.xls");
	}
	private List<TszbProcessInfoReport> operateReportWorkOrderTypeResult(
			TszbProcessInfoQuery query,String procStartTime) {
		query.setPageSize(10000);
		Page page = tszbProcessInfoManager.findPage(query);

		Collection result=page.getResult();
		List<TszbProcessInfoReport> tpirs=new ArrayList<TszbProcessInfoReport>();

		try {
			Query q = new Query ();
			q.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo GROUP BY workOrderType, "+procStartTime);
			List res =q.execute (result).getResults();
//			log.info(res);
		for (Iterator iter = res.iterator(); iter.hasNext();) {
			List ptd = (List) iter.next();
			Query q2 = new Query ();
				q2.parse ("SELECT * FROM   tx.bj12320.model.TszbProcessInfo Where workOrderType='"+ptd.get(0)+"' and "+procStartTime+"='"+ptd.get(1)+"'");
				List r =q2.execute (result).getResults();
				TszbProcessInfoReport tpir=new TszbProcessInfoReport();
				tpir.setReportDatetime(ptd.get(1).toString());
				tpir.setWorkOrderType(ptd.get(0).toString());
				tpir.setReportNum(r.size());
				tpirs.add(tpir);
			}
		} catch (QueryParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (QueryExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		log.info(tpirs);
		return tpirs;
	}

	private String genReportExcel(List<TszbProcessInfoReport> tpirs,String reportTemplateFile) {
		Map beans = new HashMap();
        beans.put("tpirs", tpirs);
        XLSTransformer transformer = new XLSTransformer();
        String xlsTemplateFileName=AppHelper.getWebAppPath()+"\\tszb\\report-templates\\"+reportTemplateFile;
        String downFileName=WebUtils.getUserInSession().getUserName()+reportTemplateFile;
        String outputFileName=AppHelper.getWebAppPath()+"\\tszb\\report-files\\"+downFileName;
        try {
			transformer.transformXLS(xlsTemplateFileName, beans, outputFileName);
		} catch (ParsePropertyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "/tszb/report-files/"+downFileName;
	}

	/**
	 * 查询未接收工单
	 * @return
	 */
	public String unReceiveTszbProcessInfoList() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);
		if(!WebUtils.getUserInSession().getSysUserType().equals(SysUserTypeEnum.BJ12320.getCode())){
			query.setOrgInfoId(orgInfoManager.getLevel1OrgInfo(WebUtils.getUserInSession().getOrgInfo()).getOrgInfoId());
		}
		Page page = tszbProcessInfoManager.findPageWithUnReceive(query);
		savePage(page,query);
		return "/tszb/un-receive-tszbProcessInfo-list.jsp";
	}
	/**
	 * 查询未办结工单
	 * @return
	 */
	public String unDealTszbProcessInfoList() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);
		if(!WebUtils.getUserInSession().getSysUserType().equals(SysUserTypeEnum.BJ12320.getCode())){
			query.setOrgInfoId(orgInfoManager.getLevel1OrgInfo(WebUtils.getUserInSession().getOrgInfo()).getOrgInfoId());
		}
		Page page = tszbProcessInfoManager.findPageWithUnDeal(query);
		savePage(page,query);
		return "/tszb/un-deal-tszbProcessInfo-list.jsp";
	}

	public String applyDelayTszbProcessInfoList() {
		TszbProcessInfoQuery query = newQuery(TszbProcessInfoQuery.class,DEFAULT_SORT_COLUMNS);
		if(!WebUtils.getUserInSession().getSysUserType().equals(SysUserTypeEnum.BJ12320.getCode())){
			query.setOrgInfoId(orgInfoManager.getLevel1OrgInfo(WebUtils.getUserInSession().getOrgInfo()).getOrgInfoId());
		}
		query.setDelayState(DelayStateEnum.APPLIED.getCode());
		Page page = tszbProcessInfoManager.findPageWithUnDeal(query);
		savePage(page,query);
		return "/tszb/apply-delay-tszbProcessInfo-list.jsp";
	}

	public String deleteTszbProcessInfo() {
		for(int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);
			Long id = new Long((String)params.get("tszbProcessInfoId"));
			TszbProcessInfo tszbProcessInfo=tszbProcessInfoManager.getById(id);
			if(tszbProcessInfo!=null&&!isNullOrEmptyString(tszbProcessInfo.getProcInstId())&&!tszbProcessInfo.getCurrActName().equals(ActivityEnum.endevent1.getCode())){

				ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(tszbProcessInfo.getProcInstId()).singleResult();
				if(processInstance!=null){
					runtimeService.deleteProcessInstance(tszbProcessInfo.getProcInstId(), "删除");
				}

			}
			tszbProcessInfoManager.removeById(id);
		}

//		runtimeService.deleteProcessInstance("501", "删除");


		Flash.current().success(DELETE_SUCCESS);
		return "!/pages/TszbProcessInfo/tszbProcessInfoList.do";
	}


	private GradeItem genGradeItem(String itemName,String termName,Long termPoint,String explain,Long gradeItemId){
		GradeItem gi=new GradeItem();
		gi.setGradeItemName(itemName);
		gi.setGradeTermName(termName);
		gi.setGradeTermPoint(termPoint);
		gi.setGradeExplain(explain);
		gi.setGradeItemId(gradeItemId);
		return gi;
	}


	public String toDealTask(){
		String taskId=getRequest().getParameter("taskId");
		getRequest().setAttribute("taskId", taskId);

		Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
		if(task.getTaskDefinitionKey().equals(ActivityEnum.bzcs.getCode())){
			List<GradeItem> lgis = genBzcsGradeItems();
			getRequest().setAttribute("gradeItems", lgis);

			List<WorkOrderQcRecord> woqrs=genBzcsQcRecordItems();
			getRequest().setAttribute("qcRecords", woqrs);

		}
		if(task.getTaskDefinitionKey().equals(ActivityEnum.xtdbsh.getCode())){//协调督办审核
			List<GradeItem> lgis = genXtdbshGradeItems();
			getRequest().setAttribute("gradeItems", lgis);
		}

		/**
		 * 网络单位签收
		 */
		if(isNullOrEmptyString(tszbProcessInfo.getReceiveTime())){
			if(task.getTaskDefinitionKey().equals(ActivityEnum.llycb.getCode())){ //联络员承办
				tszbProcessInfo.setReceiveTime(new Date());
			}

			if(task.getTaskDefinitionKey().equals(ActivityEnum.jllycb.getCode())){ //局联络员承办
				tszbProcessInfo.setReceiveTime(new Date());
			}

		}


		if(task.getTaskDefinitionKey().equals(ActivityEnum.xtdbff.getCode())){ //协调督办分发
			/**
			 * 处理一些医院需要单子实际流转到区县卫生局
			 */
			Long orgInfoId=tszbProcessInfo.getOrgInfo().getOrgInfoId();
			String orgInfoLable=tszbProcessInfo.getOrgInfo().getOrgName();
			if(!isNullOrEmptyString(tszbProcessInfo.getOrgInfo().getParentOrgCode())){
				OrgInfo oi=orgInfoManager.getByOrgCode(tszbProcessInfo.getOrgInfo().getParentOrgCode());
				orgInfoId=oi.getOrgInfoId();
				orgInfoLable=oi.getOrgName();
			}
			getRequest().setAttribute("orgInfoId", orgInfoId);
			getRequest().setAttribute("orgInfoLable", orgInfoLable);
		}

		ActivityInfo activityInfo=activityInfoManager.getLastActivityInfo(tszbProcessInfo.getTszbProcessInfoId());
		if(activityInfo!=null){
			getRequest().setAttribute("activityInfo", activityInfo);
		}


		tszbProcessInfoManager.saveOrUpdate(tszbProcessInfo);
//		ProcessInstance processInstance=runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
//		tszbProcessInfo = (TszbProcessInfo)tszbProcessInfoManager.getById(Long.valueOf(getRequest().getParameter("tszbProcessInfoId")));
		String url=getWorkOrderTypeUrl();
		return url;
	}

	/**
	 * 根据工单类型返回相应工单URL
	 * @return
	 */
	private String getWorkOrderTypeUrl() {
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.TSXTD.getCode())){
			return "/tszb/deal-tsxtd.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.TSWXCGZD.getCode())){
			return "/tszb/deal-tswxcgzd.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.JYSLD.getCode())){
			return "/tszb/deal-jysld.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.JBSLD.getCode())){
			return "/tszb/deal-jbsld.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.BYSLD.getCode())){
			return "/tszb/deal-bysld.jsp";
		}
		return "/deal-task.jsp";
	}

	public String toPrintTask(){
		String url=getWorkOrderTypeUrl4Print();
		return url;
	}

	public String toViewWorkOrderQcRecord(){
		return "/tszb/view-work-order-qc-record.jsp";
	}
	/**
	 * 根据工单类型返回相应工单URL，打印工单
	 * @return
	 */
	private String getWorkOrderTypeUrl4Print() {
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.TSXTD.getCode())){
			return "/tszb/print-tsxtd.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.TSWXCGZD.getCode())){
			return "/tszb/print-tswxcgzd.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.JYSLD.getCode())){
			return "/tszb/print-jysld.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.JBSLD.getCode())){
			return "/tszb/print-jbsld.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.BYSLD.getCode())){
			return "/tszb/print-bysld.jsp";
		}
		return "/deal-task.jsp";
	}
	public String toExportWordTask(){
		String url=getWorkOrderTypeUrl4ExportWord();
		return url;
	}
	/**
	 * 根据工单类型返回相应工单URL，导出word工单
	 * @return
	 */
	private String getWorkOrderTypeUrl4ExportWord() {
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.TSXTD.getCode())){
			return "/tszb/word-tsxtd.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.TSWXCGZD.getCode())){
			return "/tszb/word-tswxcgzd.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.JYSLD.getCode())){
			return "/tszb/word-jysld.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.JBSLD.getCode())){
			return "/tszb/word-jbsld.jsp";
		}
		if(tszbProcessInfo.getWorkOrderType().equals(WorkOrderTypeEnum.BYSLD.getCode())){
			return "/tszb/word-bysld.jsp";
		}
		return "/deal-task.jsp";
	}

	public String toViewTask(){
		String taskId=getRequest().getParameter("taskId");
		getRequest().setAttribute("taskId", taskId);

		getRequest().setAttribute("isViewTask", true);

		String url=getWorkOrderTypeUrl();
		return url;
	}

	/**
	 * 批准延时申请工单
	 * @return
	 */
	public String toApproveTask(){
		String taskId=getRequest().getParameter("taskId");
		getRequest().setAttribute("taskId", taskId);

		getRequest().setAttribute("isViewTask", true);

		getRequest().setAttribute("isApproveTask", true);

		String url=getWorkOrderTypeUrl();
		return url;
	}

	private List<WorkOrderQcRecord> genBzcsQcRecordItems() {
		List<WorkOrderQcRecord> woqrs=new ArrayList<WorkOrderQcRecord>();

		woqrs.add(genWorkOrderQcRecord("记录信息完整性","1.来话人姓名","非致命性错误"));
		woqrs.add(genWorkOrderQcRecord("记录信息完整性","2.来话人联系方式","非致命性错误"));
		woqrs.add(genWorkOrderQcRecord("记录信息完整性","3.涉及的患者姓名","致命性错误"));
		woqrs.add(genWorkOrderQcRecord("记录信息完整性","4.涉及的医疗机构名称","致命性错误"));
		woqrs.add(genWorkOrderQcRecord("记录信息完整性","5.涉及的医务人员姓名","致命性错误"));
		woqrs.add(genWorkOrderQcRecord("记录信息完整性","6.涉及的具体细节（对事件本质有影响的）","致命性错误"));
		woqrs.add(genWorkOrderQcRecord("记录信息完整性","7.向来电人说明回复方式","致命性错误"));

		woqrs.add(genWorkOrderQcRecord("形成工单理由","8.形成工单理由明确，符合逻辑","致命性错误"));

		woqrs.add(genWorkOrderQcRecord("文字表达","9.病句","非致命性错误"));
		woqrs.add(genWorkOrderQcRecord("文字表达","10.错别字","非致命性错误"));
		woqrs.add(genWorkOrderQcRecord("文字表达","11.按事情发生的先后顺序记述","非致命性错误"));

		return woqrs;
	}

	private WorkOrderQcRecord genWorkOrderQcRecord( String projectAppraisal,String assessmentContent,String errorProperties){
		WorkOrderQcRecord wqr=new WorkOrderQcRecord();
		wqr.setProjectAppraisal(projectAppraisal);
		wqr.setAssessmentContent(assessmentContent);
		wqr.setErrorProperties(errorProperties);
		return wqr;
	}

	/**
	 * 获取班长初审阶段的评分信息
	 * @return
	 */
	private List<GradeItem> genBzcsGradeItems() {
		List<GradeItem> lgis=new ArrayList<GradeItem>();
		lgis.add(genGradeItem("业务水平（30分）","形成工单合理性（10分）",new Long(10),"大部分合理扣3分；少部分合理扣6分；不合理扣10分。",new Long(1)));
		lgis.add(genGradeItem("业务水平（30分）","索取信息（20分）",new Long(20),"出现信息不全1处扣1分。医疗投诉工单诉求不明确扣5分。",new Long(2)));

		lgis.add(genGradeItem("文字水平（70分）","结构问题（20分）",new Long(20),"总体结构合理不扣分；总体结构较合理扣3分；总体结构不合理扣10分。出现局部结构不合理1处扣1分。",new Long(3)));
		lgis.add(genGradeItem("文字水平（70分）","措辞问题（10分）",new Long(10),"出现措辞问题1处扣1分。",new Long(4)));
		lgis.add(genGradeItem("文字水平（70分）","逻辑问题（20分）",new Long(20),"出现逻辑问题1处扣1分。",new Long(5)));
		lgis.add(genGradeItem("文字水平（70分）","错别字（10分）",new Long(10),"错别字出现1-2个扣2分；3-5个扣5分；6个以上扣10分。",new Long(6)));
		lgis.add(genGradeItem("文字水平（70分）","病句（10分）",new Long(10),"出现病句1处扣3分。",new Long(7)));
		return lgis;
	}
	/**
	 * 获取班长初审阶段的评分信息
	 * @return
	 */
	private List<GradeItem> genXtdbshGradeItems() {
		List<GradeItem> lgis=new ArrayList<GradeItem>();
		lgis.add(genGradeItem("业务水平（60分）","工单合理性（20分）",new Long(20),"所述事件是否应该形成工单、所适用的法规、规章等是否正确。",new Long(8)));
		lgis.add(genGradeItem("业务水平（60分）","信息全面性（30分）",new Long(30),"诉求人基本信息是否完整（10分）；对事件记录是否全面、完整，诉求是否清晰（20分）。",new Long(9)));
		lgis.add(genGradeItem("业务水平（60分）","分类正确性（10分）",new Long(10),"表扬工单无此项考核，分值加入信息全面性中。",new Long(10)));

		lgis.add(genGradeItem("文字水平（40分）","错别字（5分）",new Long(5),"1个错字3分，2个以上全扣。",new Long(11)));
		lgis.add(genGradeItem("文字水平（40分）","病句（15分）",new Long(15),"用词不当、成分残缺、次序混乱、指代不明、逻辑错误等。",new Long(12)));
		lgis.add(genGradeItem("文字水平（40分）","叙述混乱（20分）",new Long(20),"叙述事件结构混乱。",new Long(13)));

		return lgis;
	}

	private ActivityInfo activityInfo=new ActivityInfo();
	public ActivityInfo getActivityInfo() {
		return activityInfo;
	}
	public void setActivityInfo(ActivityInfo activityInfo) {
		this.activityInfo = activityInfo;
	}

	private ActivityInfoManager activityInfoManager;
	public void setActivityInfoManager(ActivityInfoManager manager) {
		this.activityInfoManager = manager;
	}

	private boolean isPass;

	public boolean getIsPass() {
		return isPass;
	}

	public void setIsPass(boolean isPass) {
		this.isPass = isPass;
	}

	private boolean isApprove;


	public boolean getIsApprove() {
		return isApprove;
	}

	public void setIsApprove(boolean isApprove) {
		this.isApprove = isApprove;
	}

	private String[] gradeTermScores;

	public void setGradeTermScores(String[] gradeTermScores) {
		this.gradeTermScores = gradeTermScores;
	}
	private GradeItemManager gradeItemManager;
	public void setGradeItemManager(GradeItemManager manager) {
		this.gradeItemManager = manager;
	}

	private File attaFile;
	private String attaFileContentType;
	private String attaFileFileName;

	public File getAttaFile() {
		return attaFile;
	}

	public void setAttaFile(File attaFile) {
		this.attaFile = attaFile;
	}

	public String getAttaFileContentType() {
		return attaFileContentType;
	}

	public void setAttaFileContentType(String attaFileContentType) {
		this.attaFileContentType = attaFileContentType;
	}

	public String getAttaFileFileName() {
		return attaFileFileName;
	}

	public void setAttaFileFileName(String attaFileFileName) {
		this.attaFileFileName = attaFileFileName;
	}

	public String applyWorkOrderDelay(){
		tszbProcessInfo.setDelayState(DelayStateEnum.APPLIED.getCode());
		tszbProcessInfoManager.saveOrUpdate(tszbProcessInfo);
		Flash.current().success("申请成功！");
		return userTasks_ACTION;
	}

	public String approveWorkOrderDelay(){
		tszbProcessInfo.setDelayState(DelayStateEnum.APPROVED.getCode());
		tszbProcessInfo.setTimeLimit(tszbProcessInfo.getTimeLimit()+tszbProcessInfo.getDelayDays());
		tszbProcessInfoManager.saveOrUpdate(tszbProcessInfo);
		Flash.current().success("批准成功！");
		return userTasks_ACTION;
	}

	private List<WorkOrderQcRecord> workOrderQcRecords;

	public List<WorkOrderQcRecord> getWorkOrderQcRecords() {
		return workOrderQcRecords;
	}

	public void setWorkOrderQcRecords(List<WorkOrderQcRecord> workOrderQcRecords) {
		this.workOrderQcRecords = workOrderQcRecords;
	}

	public String dealTask(){
		tszbProcessInfo.setLastOperateUserInfoId(WebUtils.getUserInSession().getUserInfoId());
		tszbProcessInfoManager.saveOrUpdate(tszbProcessInfo);
		if (!isNullOrEmptyString(tszbProcessInfo.getIsReject())&&tszbProcessInfo.getIsReject()==1) {//工单报废
			runtimeService.deleteProcessInstance(tszbProcessInfo.getProcInstId(), tszbProcessInfo.getRejectReason());
			tszbProcessInfo.setRejectTime(new Date());
			tszbProcessInfoManager.saveOrUpdate(tszbProcessInfo);
			return userTasks_ACTION;
		}

		String taskId=getRequest().getParameter("taskId");
		Task task=taskService.createTaskQuery().taskId(taskId).singleResult();

		activityInfo.setTszbProcessInfoId(tszbProcessInfo.getTszbProcessInfoId());
		activityInfo.setUserInfoId(WebUtils.getUserInSession().getUserInfoId());
		activityInfo.setOperatorName(WebUtils.getUserInSession().getRealName());
		activityInfo.setReceiveTime(task.getCreateTime());
		activityInfo.setFinishTime(new Date());
		activityInfo.setActivityName(task.getTaskDefinitionKey());
		if(!isNullOrEmptyString(activityInfo.getIncomingCallContent())){
			activityInfo.setIncomingCallContentBak(tszbProcessInfo.getIncomingCallContent());
			tszbProcessInfo.setIncomingCallContent(activityInfo.getIncomingCallContent());
		}
		activityInfoManager.save(activityInfo);

		taskService.claim(taskId, WebUtils.getUserInSession().getUserInfoId()+"");
		Map<String, Object> vars = new HashMap<String, Object>();
		vars.put("isPass", isPass);
		if(isPass){
			tszbProcessInfo.setLastOperateIsPass(new Long(1));
		}else{
			tszbProcessInfo.setLastOperateIsPass(new Long(0));
		}

		dealTaskWtihActivity(task, vars);

		taskService.complete(task.getId(), vars);

		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
		if(processInstance!=null){
			tszbProcessInfo.setCurrActName(((ExecutionEntity)processInstance).getActivityId());
			tszbProcessInfo.setCurrSysUserType(ActivitySysUserTypeEnum.getByCode(tszbProcessInfo.getCurrActName()).getDesc());
		}

		uploadAttaFile();

		tszbProcessInfoManager.saveOrUpdate(tszbProcessInfo);
		Flash.current().success("办理完成！");
		return userTasks_ACTION;
	}

	private WorkOrderQcRecordManager workOrderQcRecordManager;
	public void setWorkOrderQcRecordManager(WorkOrderQcRecordManager manager) {
		this.workOrderQcRecordManager = manager;
	}
	/**
	 * 处理每个活动需要处理的逻辑
	 * @param task
	 * @param vars
	 */
	private void dealTaskWtihActivity(Task task, Map<String, Object> vars) {
		if(task.getTaskDefinitionKey().equals(ActivityEnum.bzcs.getCode())){//班长初审
			if(!isNullOrEmptyString(gradeTermScores)&&isPass){
				/* 删除以前评分
				if(!isNullOrEmptyString(tszbProcessInfo.getBzcsScore())){//已评过分数
					ActivityInfoQuery query = newQuery(ActivityInfoQuery.class,ActivityInfoAction.DEFAULT_SORT_COLUMNS);
					query.setTszbProcessInfoId(tszbProcessInfo.getTszbProcessInfoId());
					query.setActivityName(ActivityEnum.bzcs.getCode());
					Page page = activityInfoManager.findPage(query);
					Set<GradeItem> lgis=((ActivityInfo)page.getResult().get(page.getResult().size()-1)).getGradeItems();
					for (GradeItem gradeItem : lgis) {
						gradeItemManager.removeById(gradeItem.getGradeItemId());
					}
				}
				*/
				List<GradeItem> lgis = genBzcsGradeItems();
				tszbProcessInfo.setBzcsScore(new Long(0));
				for(int i=0;i<gradeTermScores.length;i++){
					GradeItem gi=lgis.get(i);
					gi.setGradeTermScore(new Long(gradeTermScores[i]));
					gi.setActivityInfoId(activityInfo.getActivityInfoId());
					tszbProcessInfo.setBzcsScore(tszbProcessInfo.getBzcsScore()+gi.getGradeTermScore());
					gradeItemManager.save(gi);
				}
			}
			tszbProcessInfo.setChushenPerson(WebUtils.getUserInSession().getRealName());

			for (WorkOrderQcRecord workOrderQcRecord : workOrderQcRecords) {
				workOrderQcRecordManager.save(workOrderQcRecord);
			}
			tszbProcessInfo.setQcPerson(WebUtils.getUserInSession().getRealName());
			tszbProcessInfo.setQcTime(new Date());

		}
		if(task.getTaskDefinitionKey().equals(ActivityEnum.xtdbsh.getCode())){//协调督办审核
			if(!isNullOrEmptyString(gradeTermScores)&&isPass){
				List<GradeItem> lgis = genXtdbshGradeItems();
				tszbProcessInfo.setXtdbshScore(new Long(0));
				for(int i=0;i<gradeTermScores.length;i++){
					GradeItem gi=lgis.get(i);
					gi.setGradeTermScore(new Long(gradeTermScores[i]));
					gi.setActivityInfoId(activityInfo.getActivityInfoId());
					tszbProcessInfo.setXtdbshScore(tszbProcessInfo.getXtdbshScore()+gi.getGradeTermScore());
					gradeItemManager.save(gi);
				}
			}
			// 建议、表扬和未形成告知单不用中心领导审核。
			if (tszbProcessInfo.getWorkOrderType().equals(
					WorkOrderTypeEnum.JYSLD.getCode())
					|| tszbProcessInfo.getWorkOrderType().equals(
							WorkOrderTypeEnum.BYSLD.getCode())
					|| tszbProcessInfo.getWorkOrderType().equals(
							WorkOrderTypeEnum.TSWXCGZD.getCode())) {
				vars.put("is_xtdbsh_2_xtdbff", true);
			}else{
				vars.put("is_xtdbsh_2_xtdbff", false);
			}
			tszbProcessInfo.setShenhePerson(WebUtils.getUserInSession().getRealName());
		}

		if (task.getTaskDefinitionKey().equals(ActivityEnum.zgzrsd.getCode())) {//主管主任审定

		}

		if(task.getTaskDefinitionKey().equals(ActivityEnum.xtdbff.getCode())){ //协调督办分发
			OrgInfo oi=orgInfoManager.getById(tszbProcessInfo.getOrgInfoId());
			vars.put("SysUserType", oi.getSysUserType());
			vars.put("orgInfoId", oi.getOrgInfoId());
			vars.put("orgName", oi.getOrgName());
			tszbProcessInfo.setWorkOrderIssueTime(new Date());

		}



		if(task.getTaskDefinitionKey().equals(ActivityEnum.jllyff.getCode())){ //局联络员分发
			vars.put("chengbanOrgInfoId", tszbProcessInfo.getChengbanOrgInfoId());
		}

		if(task.getTaskDefinitionKey().equals(ActivityEnum.jgfk.getCode())){ //结果反馈
			tszbProcessInfo.setWorkOrderDealTime(new Date());
		}

		if(task.getTaskDefinitionKey().equals(ActivityEnum.jjgfk.getCode())){ //局结果反馈
			tszbProcessInfo.setWorkOrderDealTime(new Date());
		}

		if(task.getTaskDefinitionKey().equals(ActivityEnum.xtdbgd.getCode())){ //协调督办归档
			vars.put("isApprove", isApprove);
			vars.put("SysUserType", tszbProcessInfo.getOrgInfo().getSysUserType());
			if(isApprove){
				tszbProcessInfo.setIsProcEnd(1L);
				tszbProcessInfo.setProcEndTime(new Date());
				tszbProcessInfo.setCurrActName("endevent1");

				//流程结束，向呼叫中心发送结果数据
				syncData2cc();

			}
		}
	}

	/**
	 * 调用呼叫中心接口，传递工单办理结果
	 */
	private void syncData2cc() {
		StringBuffer xmlData=new StringBuffer("<XMLInfo><GlobalInfo><ExecuteTime></ExecuteTime></GlobalInfo><Censure><ProvBOSS><ticketflow>");
		xmlData.append(tszbProcessInfo.getCcWorkfflowid()+"</ticketflow><ticketId>");
		xmlData.append(tszbProcessInfo.getCcTicketid()+"</ticketId><dealContent>");
		xmlData.append(tszbProcessInfo.getDealResult()+"</dealContent></ProvBOSS></Censure></XMLInfo>");
		log.info(xmlData.toString());
		try {
			JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
			Client client = dcf.createClient("http://10.1.1.12/hollycrm/services/test?wsdl");
			Object[] res = client.invoke("updateTicket", xmlData.toString());
			log.info(res[0]);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 上传工单附件
	 */
	private void uploadAttaFile() {
		if (attaFile != null) {
			String fileFormat = WebUtils.getExtention(attaFileFileName);
			String newFileName = tszbProcessInfo.getTszbProcessInfoId() + fileFormat;
			File newFile = new File(ServletActionContext.getServletContext()
					.getRealPath("/tszb/atta-files")
					+ "/" + newFileName);
			WebUtils.copy(attaFile, newFile);

			tszbProcessInfo.setAttaFileName(newFileName);
		}
	}

	/**进入更新页面*/
	public String edit() {
		return EDIT_JSP;
	}

	/**保存更新对象*/
	public String update() {
		tszbProcessInfoManager.update(this.tszbProcessInfo);
		Flash.current().success(UPDATE_SUCCESS);
		return LIST_ACTION;
	}

	/**删除对象*/
	public String delete() {
		for(int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);
			Long id = new Long((String)params.get("tszbProcessInfoId"));
			tszbProcessInfoManager.removeById(id);
		}
		Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}

	public String toStartTsxtd(){
		return "/tszb/start-tsxtd.jsp";
	}
	public String toStartTswxcgzd(){
		return "/tszb/start-tswxcgzd.jsp";
	}
	public String toStartJysld(){
		return "/tszb/start-jysld.jsp";
	}
	public String toStartJbsld(){
		return "/tszb/start-jbsld.jsp";
	}
	public String toStartBysld(){
		return "/tszb/start-bysld.jsp";
	}


	public String startProcess(){
		tszbProcessInfoManager.startProcess(tszbProcessInfo);

		Flash.current().success(CREATED_SUCCESS);
		return userTasks_ACTION;
	}

	public String processImg(){
		Set<ActivityInfo> ais=tszbProcessInfo.getActivityInfos();
//		Map<String, BPMNShape> mb=ActivityBPMNShapeEnum.toMap();
		Set<BPMNShape> acs=new HashSet<BPMNShape>();
		for (ActivityInfo activityInfo : ais) {
			acs.add(ActivityBPMNShapeEnum.getBPMNShape(activityInfo.getActivityName()).setOperatorName(activityInfo.getOperatorName()));
		}
		getRequest().setAttribute("acs", acs);

		getRequest().setAttribute("currAc", ActivityBPMNShapeEnum.getBPMNShape(tszbProcessInfo.getCurrActName()));

		return "/tszb/process-img.jsp";
	}
	public String addCanddidateUser(){
		List<ProcessInstance> ls=runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(getRequest().getParameter("tszbProcessInfoId")).list();
		if(ls.size()>0){
			ProcessInstance pi=ls.get(0);
			List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
			log.info(tasks.size());
			if(tasks.size()>0){
				Task t=tasks.get(0);
				taskService.addCandidateUser(t.getId(), getRequest().getParameter("userId"));
			}
		}
		return "";
	}

}
